import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public abstract class GenerateFile 
{
	// Get page content
	public static void save(Database base, String file) throws IOException
	{
		// Create file
		BufferedWriter stream = new BufferedWriter(new FileWriter(file));
		stream.write("Famille;Espece;Identifiant;Longueur;Type;Anticodon;Position;Seq;Str;Score\n");
					
		for (Arn a : base.db)
		{
			stream.write(a.getFamily() + ";" + a.getSpecies() + ";" + a.getId() + ";" +
		                 a.getLength() + ";" + a.getType() + ";" + a.getAnticodon() + ";" + 
					     a.getPosition() + ";" + a.getSeq() + ";" + a.getStr() + ";" +
		                 a.getScore() + ";\n");
		}	
		stream.close();
	}
	
	// Retrieve xls files data in databases
	public static void load(Database base, String file) throws IOException
	{
		// Read file
		BufferedReader stream = new BufferedReader(new FileReader(file));
		String         line   = stream.readLine();
		String[]       arg    = null;
		Arn            a      = new Arn();
		
		while ((line = stream.readLine()) != null)
		{			
			arg = line.split(";");
			a.setFamily(arg[0]);
			a.setSpecies(arg[1]);
			a.setId(arg[2]);
			a.setLength(arg[3]);
			a.setType(arg[4]);
			a.setAnticodon(arg[5]);
			a.setPosition(arg[6]);
			a.setSeq(arg[7]);
			a.setStr(arg[8]);
			a.setScore(arg[9]);
			
			base.add(a);
			a = new Arn();
		}
	}
	
	// Retrieve xls statistics files (anticodons) data in databases
	public static Stats stats(Database data, String file) throws IOException
	{
		// On créé notre structure pour contenir les stats
		Stats s = new Stats();
		
		// On parcourt la base de données
		for (Arn a : data.db)
		{
			String ac  = a.getAnticodon();
			int    pos = Integer.parseInt(a.getPosition())-1;
			String seq = a.getSeq();
			String acs = seq.substring(pos, pos+3);
			
			// Si l'anticodon est bien positionné
			if (ac.equals(acs))
			{
				// On segmente la chaîne dans les stats
				s.cut(seq, ac, pos);
			}
		}

		// Une fois terminé, on sauvegarde les stats dans le fichier
		s.save(file);
		
		return s;
	}
}
